/*
 * material.cpp
 *
 *  Created on: Jan 12, 2011
 *      Author: dima
 */

#include "material.h"





GLuint loadShader(GLenum type, const char* src)
{

	GLuint shader;
	GLint compiled;

	shader = glCreateShader(type);
	if( shader == 0)
	{
		return 0;
	}


	glShaderSource(shader, 1, &src, NULL);
	glCompileShader(shader);
	// todo shader compile status
	return shader;
}

GLuint createProgram(GLuint vertexShader, GLuint fragmentShader)
{
	GLuint program;
	program = glCreateProgram();

	glAttachShader(program, vertexShader);
	glAttachShader(program, fragmentShader);
	glLinkProgram(program);


	GLint linked;
	glGetProgramiv(program, GL_LINK_STATUS, &linked);

	if(!linked)
	{
		GLint infoLen = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);

		if(infoLen > 1)
		{
			char* infoLog = new char[infoLen];
			glGetProgramInfoLog(program, infoLen, NULL, infoLog);
			ERROR("Error linking program:\n%s\n", infoLog);
			free(infoLog);
		}
		glDeleteProgram(program);
		return 0;


	}


	return program;
}

inline void bindMaterial(Material* mat)
{
	mat->bind(mat);
}

void materialBind_Simple(Material* mat)
{
	MaterialData_Simple* data = (MaterialData_Simple*)(mat->materialData);

	GLuint handle = glGetAttribLocation(mat->program, "a_color");
	glVertexAttrib4f(handle, data->defaultColor[0], data->defaultColor[1],
		data->defaultColor[2], data->defaultColor[3]);


	glBindAttribLocation(mat->program, handle, "a_color");

}

